package server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * Minicat的主类
 * @author chengzhj
 * @data 2021/8/26 10:06 下午
 */
public class Bootstrap {

    Mapper mapper = new Mapper();

    // 定义socket监听的端口号
    private int port;

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start() throws Exception {

        // 加载解析配置文件
        // loadServlet();
        loadServer();
        loadMapper();

        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize = 50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );

        /**
         * 完成Minicat1.0版本
         * 需求：浏览器请求http://localhost:8080，返回一个固定的字符串到页面"Hello Minicat!"
         */
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("========>>>>>Minicat start on port:" + port);

        /*while (true) {
            Socket socket = serverSocket.accept();
            // 有了socket，接收到请求，获取输出流
            OutputStream outputStream = socket.getOutputStream();
            String data = "Hello Minicat!";
            String responseText = HttpProtocolUtil.getHttpHeader200(data.getBytes().length) + data;
            outputStream.write(responseText.getBytes());
            socket.close();
        }*/

        /**
         * 完成Minicat 2.0版本
         * 需求：封装Request和Response对象，返回html静态资源文件
         */
        /*while (true) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            response.outputHtml(request.getUrl());

            socket.close();
        }*/

        /**
         * 完成Minicat 3.0版本
         * 需求：封装Request和Response对象，返回html静态资源文件
         */
        /*while (true) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            if (servletMap.get(request.getUrl()) == null) {
                // 静态资源
                response.outputHtml(request.getUrl());
            } else {
                // 动态资源
                HttpServlet httpServlet = servletMap.get(request.getUrl());
                httpServlet.service(request, response);
            }

            socket.close();
        }*/

        // 多线程改造
        /*while (true) {
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket, servletMap);
            requestProcessor.start();
        }*/

        System.out.println("====> 使用线程池进行多线程改造");
        // 多线程改造(使用线程池)
        while (true) {
            Socket socket = serverSocket.accept();
            RequestProcessorMapper requestProcessorMapper = new RequestProcessorMapper(socket, mapper);
            // requestProcessor.start();
            threadPoolExecutor.execute(requestProcessorMapper);
        }

    }

    private Map<String, HttpServlet> servletMap = new HashMap<String, HttpServlet>();

    // 读取web.xml
    private void loadServlet() {
        InputStream webConfig = this.getClass().getClassLoader().getResourceAsStream("web.xml");
        SAXReader webReader = new SAXReader();

        try {
            Document document = webReader.read(webConfig);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element = selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();

                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                servletMap.put(urlPattern, (HttpServlet) Class.forName(servletClass).newInstance());
            }

        } catch (DocumentException | ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    // 加载server.xml并解析
    public void loadServer() {
        InputStream serverConfig = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader serverReader = new SAXReader();

        try {
            Document document = serverReader.read(serverConfig);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//Service");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element = selectNodes.get(i);
                // <Connector port="8080"/>
                Element connector = (Element) element.selectSingleNode("Connector");
                String portStr = connector.attributeValue("port");
                // 访问端口
                port = Integer.parseInt(portStr);
                System.out.println("port：" + port);
                Element engine = (Element) element.selectSingleNode("Engine");
                // <Host name="localhost" appBase="/Users/kyrin/lagou/project/2-1tomcat/Minicat/src/main/resources/webapps"></Host>
                Element hostElement = (Element) engine.selectSingleNode("Host");
                // 路径
                String name = hostElement.attributeValue("name");
                // 外部servlet所在的路径
                String appBase = hostElement.attributeValue("appBase");
                Mapper.Host host = new Mapper.Host(name, appBase);
                mapper.setHost(host);
                System.out.println("name:" + name);
                System.out.println("appBase:" + appBase);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 读取appBese下的context并封装到Mapper
    private void loadMapper() {
        // 获取appBase
        String appBase = mapper.getHost().getAppBase();
        // 获取webapps下面的所有servlet
        Mapper.Host host = mapper.getHost();

        File file = new File(appBase);
        try {
            file = file.getCanonicalFile();
        } catch (IOException e) {
            System.out.println("获取webapps下文件失败");
            e.printStackTrace();
        }
        // [demo1, demo2]
        String[] files = file.list();

        // 循环webapps下的所有项目
        for (int i = 0; i < files.length; i++) {
            File dir = new File(appBase, files[i]);
            if (dir.isDirectory()) {
                loadWebAppsServlet(dir.getName(), dir.getPath(), "webapps", host);
            }
        }
    }

    // 加载servlet并封装
    private void loadWebAppsServlet(String name, String path, String appBase, Mapper.Host host){
        // 读取部署项目的配置文件
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(appBase+"/"+ name +"/web.xml");
        SAXReader saxReader = new SAXReader();
        try {
            Document read = saxReader.read(resourceAsStream);
            Element rootElement = read.getRootElement();
            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            Element element = selectNodes.get(0);
            Element selectNameElement = (Element)element.selectSingleNode("servlet-name");
            // <servlet-name>ghc</servlet-name>
            String servletName = selectNameElement.getStringValue();
            Element selectClassElement = (Element)element.selectSingleNode("servlet-class");
            //<servlet-class>server.GhcServlet</servlet-class>
            String servletClass = selectClassElement.getStringValue();
            Element servletMapping = (Element)rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
            String urlPatten = servletMapping.selectSingleNode("url-pattern").getStringValue();
            // 解析出的url中第一个带/,删除这个/
            urlPatten = urlPatten.substring(1);
            MyClassLoader myClassLoader = new MyClassLoader(path);

            // 自定义类加载器
            Class<?> aClass = myClassLoader.findClass(servletClass);
            HttpServlet httpServlet = (HttpServlet)aClass.newInstance();
            // 加入context
            host.addContext(name, urlPatten, httpServlet);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Minicat的主程序启动入口
     * @param args
     */
    public static void main(String[] args) throws Exception {

        Bootstrap bootstrap = new Bootstrap();
        try {
            // 启动Minicat
            bootstrap.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
